#!/usr/bin/perl -wc

package RFCMail::Util::PackIt::Convert;

use strict;
use bytes;


sub get_u32 {
    my ($self, $n) = @_;
    $n = 1
	if not defined($n);
    return (unpack("N[$n]", $self->read(4 * $n)));
}


sub put_u32 {
    my $self = shift;
    $self->write(pack('N*', @_));
    return ($self);
}


sub get_u8 {
    my ($self, $n) = @_;
    $n = 1
	if not defined($n);
    return (unpack("C[$n]", $self->read($n)));
}


sub put_u8 {
    my $self = shift;
    $self->write(pack('C*', @_));
    return ($self);
}


sub get_var8 {
    my ($self, $n) = @_;
    $n = 1
	if not defined($n);
    my @vars;
    for (1..$n) { push @vars, $self->read(get_u8($self)) }
    return (wantarray ? @vars : $vars[0]);
}


sub put_var8 {
    my $self = shift;
    $self->write(pack('(C/a*)*', @_));
    return ($self);
}


sub get_domain {
    my ($self, $n) = @_;
    $n = 1
	if not defined($n);
    my (@names, @dn, $part);
    for (1..$n) {
	@dn = ();
	while ($part = get_var8($self)) { push @dn, $part }
	push @names, join('.', @dn);
    }
    return (wantarray ? @names : $names[0]);
}


sub put_domain {
    my $self = shift;
    for (@_) {
	put_var8($self, split(/\./), "");
    }
    return ($self);
}


sub get_hex {
    my ($self, $n) = @_;
    $n = 1
	if not defined($n);
    return (unpack('H*', $self->read($n)));
}


sub put_hex {
    my ($self, $data) = @_;
    $self->write(pack('H*', $data));
    return ($self);
}

1;
